package controllers

import (
	"bsm/logger"
	"bsm/middleware"
	"bsm/models"
	"bsm/services"
	"fmt"
	"net/http"
	"os"
	"strconv"

	"github.com/gin-gonic/gin"
)

type ImportController interface {
	Import(ctx *gin.Context)
}

type importControllerImpl struct {
	importSvc services.ImportService
	authSvc   services.AuthService
}

func NewImportController(importSvc services.ImportService, authSvc services.AuthService) ImportController {
	return &importControllerImpl{
		importSvc: importSvc,
		authSvc:   authSvc,
	}
}

func (c *importControllerImpl) Import(ctx *gin.Context) {
	// 验证用户信息
	if !c.authSvc.JWTAuthUser(ctx) {
		return
	}

	form, err := ctx.MultipartForm()
	if err != nil {
		ctx.JSON(http.StatusBadRequest, models.ResponseModel{
			Code: 1,
			Msg:  "上传文件数据错误",
			Data: "",
		})
		return
	}
	// 1. 从表单中获取文件和其他字段
	files := form.File["file"]                                   // 文件字段名为 "file"
	designType, err := strconv.Atoi(form.Value["designType"][0]) // 设计类型字段名为 "designType"
	if err != nil {
		ctx.JSON(http.StatusBadRequest, models.ResponseModel{
			Code: 1,
			Msg:  "设计类型参数错误",
			Data: "",
		})
		return
	}

	// 2. 检查文件是否为空
	if len(files) == 0 {
		ctx.JSON(http.StatusBadRequest, "请至少上传一个文件")
		return
	}

	uppath := "./uploads/"
	if err := os.Chmod(uppath, 0750); err != nil { // 设置目录权限为750
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "Import",
		}).Errorf("设置上传文件目录权限失败: %v", err)
	}

	// 3. 处理文件
	results := make([]models.ImportResult, 0, len(files))
	successCount := 0
	for _, file := range files {
		result := models.ImportResult{FileName: file.Filename}

		filepath := uppath + file.Filename

		// 保存文件到本地或其他存储位置
		if err := ctx.SaveUploadedFile(file, filepath); err != nil {
			logger.WithFields(map[string]interface{}{
				"layer":     "controller",
				"operation": "Import",
			}).Errorf("保存导入文件失败: %v", err)
			ctx.JSON(http.StatusInternalServerError, models.ResponseModel{
				Code: 1,
				Msg:  "导入文件保存失败",
				Data: "",
			})
			return
		}

		// 调用服务层的导入方法
		var err error
		uid := middleware.GetCurrentUserID(ctx)
		if err = c.importSvc.ImportBudgetSheet(filepath, designType, uid); err != nil {
			logger.WithFields(map[string]interface{}{
				"layer":     "controller",
				"operation": "Import-ImportBudgetSheet",
			}).Errorf("导入文件失败: %v", err)
			result.Message = fmt.Sprintf("导入失败:%v", err)
			result.IsSuccess = false
			results = append(results, result)
			continue
		}
		result.Message = "导入成功"
		result.IsSuccess = true
		result.Filesize = file.Size
		results = append(results, result)

		successCount++
	}
	// 4. 返回结果
	ctx.JSON(http.StatusOK, models.ResponseModel{
		Code:  0,
		Msg:   "文件导入完成",
		Count: successCount, // 成功导入的文件数量
		Data:  results,
	})
}
